package com.java.util.servlet;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson2.JSONObject;
import com.java.util.MyCons;
import com.java.util.resp.BaseRespone;

public class ServletUtil {
	
	public static ServletRequestAttributes getRequestAttributes() {
		return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	}

	public static HttpServletRequest getRequest() {
		return getRequestAttributes().getRequest();
	}

	public static HttpSession getSession() {
		return getRequest().getSession();
	}
	
	public static boolean isAjax(HttpServletRequest request) {
		boolean isAsyncStarted = request.isAsyncStarted();
		return isAsyncStarted;
	}
	
	public static boolean adminIsLogin() {
		Object user = getSession().getAttribute(MyCons.ADMIN_ROLE);
		if(user == null) {
			return false;
		}
		return true;
	}
	
	public static boolean userIsLogin() {
		Object user = getSession().getAttribute(MyCons.USER_ROLE);
		if(user == null) {
			return false;
		}
		return true;
	}
	
	public static void noLogin(HttpServletResponse response) throws Exception{
	     response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
	     response.setCharacterEncoding("UTF-8");
	     response.setContentType("application/json; charset=utf-8");
	     BaseRespone res = new BaseRespone(HttpServletResponse.SC_UNAUTHORIZED, "未登录");
	     PrintWriter out = null ;
	     out = response.getWriter();
	     out.write(JSONObject.toJSONString(res));
	     out.flush();
	     out.close();
	 }
}
